package lc20240529;

import lc20240526.ListNode;

/**
 * @author 不知名帅哥
 * @version 1.0
 * @description 给你一个链表，删除链表的倒数第 n 个结点，并且返回链表的头结点。
 * @date 2024/5/29 21:12
 */
public class DeleteElementOfList {
    public static void main(String[] args) {
        ListNode head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5)))));
        ListNode newHead = removeNthFromEnd(head, 2);
        while (newHead != null) {
            System.out.print(newHead.val + " ");
            newHead = newHead.next;
        }

    }

    public static ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode res = head;
        int count = 0;
        while (res != null) {
            count++;
            res = res.next;
        }
        ListNode p = dummy;
        ListNode q = p.next;

        while (true) {
            count--;
            if (count == n - 1) {
                p.next = q.next;
                break;
            }
            p = p.next;
            q = q.next;
        }
        return dummy.next;
    }
}
